from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status

def custom_exception_handler(exc, context):
    # 调用默认的异常处理器以获取标准的错误响应
    response = exception_handler(exc, context)

    # 如果响应为 None，则创建一个新的响应
    if response is None:
        return Response(data={
            'message': 'An unexpected error occurred',
            'code': status.HTTP_500_INTERNAL_SERVER_ERROR,
            'data': {}
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR, content_type='application/json')

    # 自定义错误响应格式
    return Response(data={
        'message': response.data.get('detail', 'An error occurred'),
        'code': response.status_code,
        'data': response.data
    }, status=response.status_code, content_type='application/json')
